<?php

namespace App\Http\Middleware;

use App\Entities\QrcodeAdvertisingEntity;
use App\Entities\QrcodeAdvertisingModel;
use App\Services\Cache\Key;
use App\Services\Code\HttpResponse;
use Carbon\Carbon;
use Closure;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

/**
 * 登陆检查
 * Class LoginCheck
 * @package App\Http\Middleware
 */
class LoginCheck
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $userId = (int) $request->input('user_id');
        if ($userId === 0) {
            return response()->json(HttpResponse::respFail(403, '末登陆'));
        }

        //分销
        $openid = (string)$request->input('openid', '');
        $agentId = (int)Redis::connection()->get(Key::getDistribution($openid));
        if ($openid && $agentId > 0 && !$qrcodeAdvertisingEntity = QrcodeAdvertisingEntity::findByUserId($userId)) {
            $qrcodeAdvertisingEntity = new QrcodeAdvertisingEntity(new QrcodeAdvertisingModel());
            $qrcodeAdvertisingEntity->setCreateAt(Carbon::now()->getTimestamp());
            $qrcodeAdvertisingEntity->setAgentid($agentId);
            $qrcodeAdvertisingEntity->setUid($userId);
            $qrcodeAdvertisingEntity->setUpdateAt(Carbon::now()->getTimestamp());
            $qrcodeAdvertisingEntity->save();
            Log::info('新增分销关系', $qrcodeAdvertisingEntity->toArray());
        }

        return $next($request);
    }
}
